package com.smartcampusbackend.controller;

import com.smartcampusbackend.model.RepairApplication;
import com.smartcampusbackend.model.RepairStatusLog;
import com.smartcampusbackend.model.RepairTypeConfig;
import com.smartcampusbackend.service.RepairApplicationService;
import com.smartcampusbackend.service.RepairTypeConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ContentDisposition;
import java.nio.charset.StandardCharsets;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/repair")
public class RepairApplicationController {
    private static final Logger logger = LoggerFactory.getLogger(RepairApplicationController.class);
    
    @Autowired
    private RepairApplicationService repairApplicationService;
    
    @Autowired
    private RepairTypeConfigService repairTypeConfigService;
    
    // 获取维修类型列表
    @GetMapping("/types")
    public ResponseEntity<List<RepairTypeConfig>> getRepairTypes() {
        logger.info("获取维修类型列表");
        List<RepairTypeConfig> types = repairTypeConfigService.getActiveTypes();
        return ResponseEntity.ok(types);
    }
    
    // 提交维修申请
    @PostMapping("/submit")
    public ResponseEntity<Boolean> submitApplication(
            @RequestParam("applicantId") Integer applicantId,
            @RequestParam("applicantName") String applicantName,
            @RequestParam("applicantRole") String applicantRole,
            @RequestParam("repairType") String repairType,
            @RequestParam("location") String location,
            @RequestParam("description") String description,
            @RequestParam(value = "priority", defaultValue = "普通") String priority,
            @RequestParam(value = "photos", required = false) List<MultipartFile> photos) {
        
        logger.info("提交维修申请，申请人: {}, 类型: {}, 地点: {}", applicantName, repairType, location);
        
        try {
            RepairApplication application = new RepairApplication();
            application.setApplicantId(applicantId);
            application.setApplicantName(applicantName);
            application.setApplicantRole(applicantRole);
            application.setRepairType(repairType);
            application.setLocation(location);
            application.setDescription(description);
            application.setPriority(priority);
            
            boolean result = repairApplicationService.submitApplication(application, photos);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("提交维修申请失败", e);
            return ResponseEntity.badRequest().body(false);
        }
    }
    
    // 获取用户的维修申请列表
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<RepairApplication>> getUserApplications(@PathVariable Integer userId) {
        logger.info("获取用户维修申请列表，用户ID: {}", userId);
        List<RepairApplication> applications = repairApplicationService.getUserApplications(userId);
        return ResponseEntity.ok(applications);
    }
    
    // 获取维修人员的维修申请列表
    @GetMapping("/assignee/{assigneeId}")
    public ResponseEntity<List<RepairApplication>> getAssigneeApplications(@PathVariable Integer assigneeId) {
        logger.info("获取维修人员维修申请列表，维修人员ID: {}", assigneeId);
        List<RepairApplication> applications = repairApplicationService.getAssigneeApplications(assigneeId);
        return ResponseEntity.ok(applications);
    }
    
    // 获取所有维修申请（管理员用）
    @GetMapping("/all")
    public ResponseEntity<List<RepairApplication>> getAllApplications() {
        logger.info("获取所有维修申请");
        List<RepairApplication> applications = repairApplicationService.getAllApplications();
        return ResponseEntity.ok(applications);
    }
    
    // 根据状态获取维修申请列表
    @GetMapping("/status/{status}")
    public ResponseEntity<List<RepairApplication>> getApplicationsByStatus(@PathVariable String status) {
        logger.info("根据状态获取维修申请列表，状态: {}", status);
        List<RepairApplication> applications = repairApplicationService.getApplicationsByStatus(status);
        return ResponseEntity.ok(applications);
    }
    
    // 获取维修申请详情
    @GetMapping("/{id}")
    public ResponseEntity<RepairApplication> getApplicationById(@PathVariable Long id) {
        logger.info("获取维修申请详情，ID: {}", id);
        RepairApplication application = repairApplicationService.getApplicationById(id);
        if (application == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(application);
    }
    
    // 分配维修人员
    @PostMapping("/{id}/assign")
    public ResponseEntity<Boolean> assignRepairman(
            @PathVariable Long id,
            @RequestParam("assigneeId") Integer assigneeId,
            @RequestParam("assigneeName") String assigneeName) {
        
        logger.info("分配维修人员，申请ID: {}, 维修人员: {}", id, assigneeName);
        
        boolean result = repairApplicationService.assignRepairman(id, assigneeId, assigneeName);
        return ResponseEntity.ok(result);
    }
    
    // 开始维修
    @PostMapping("/{id}/start")
    public ResponseEntity<Boolean> startRepair(
            @PathVariable Long id,
            @RequestParam("operatorId") Integer operatorId,
            @RequestParam("operatorName") String operatorName) {
        
        logger.info("开始维修，申请ID: {}, 操作人: {}", id, operatorName);
        
        boolean result = repairApplicationService.startRepair(id, operatorId, operatorName);
        return ResponseEntity.ok(result);
    }
    
    // 完成维修
    @PostMapping("/{id}/complete")
    public ResponseEntity<Boolean> completeRepair(
            @PathVariable Long id,
            @RequestParam("operatorId") Integer operatorId,
            @RequestParam("operatorName") String operatorName,
            @RequestParam("actualDuration") String actualDuration) {
        
        logger.info("完成维修，申请ID: {}, 操作人: {}, 用时: {}", id, operatorName, actualDuration);
        
        boolean result = repairApplicationService.completeRepair(id, operatorId, operatorName, actualDuration);
        return ResponseEntity.ok(result);
    }
    
    // 取消申请
    @PostMapping("/{id}/cancel")
    public ResponseEntity<Boolean> cancelApplication(
            @PathVariable Long id,
            @RequestParam("operatorId") Integer operatorId,
            @RequestParam("operatorName") String operatorName,
            @RequestParam("cancelReason") String cancelReason) {
        
        logger.info("取消维修申请，申请ID: {}, 操作人: {}, 原因: {}", id, operatorName, cancelReason);
        
        boolean result = repairApplicationService.cancelApplication(id, operatorId, operatorName, cancelReason);
        return ResponseEntity.ok(result);
    }
    
    // 编辑申请
    @PutMapping("/{id}")
    public ResponseEntity<Boolean> updateApplication(
            @PathVariable Long id,
            @RequestParam("repairType") String repairType,
            @RequestParam("location") String location,
            @RequestParam("description") String description,
            @RequestParam(value = "priority", defaultValue = "普通") String priority,
            @RequestParam(value = "photos", required = false) List<MultipartFile> photos) {
        
        logger.info("编辑维修申请，ID: {}", id);
        
        try {
            RepairApplication application = repairApplicationService.getApplicationById(id);
            if (application == null) {
                return ResponseEntity.notFound().build();
            }
            
            application.setRepairType(repairType);
            application.setLocation(location);
            application.setDescription(description);
            application.setPriority(priority);
            
            boolean result = repairApplicationService.updateApplication(application, photos);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("编辑维修申请失败", e);
            return ResponseEntity.badRequest().body(false);
        }
    }
    
    // 获取维修申请的状态变更记录
    @GetMapping("/{id}/logs")
    public ResponseEntity<List<RepairStatusLog>> getStatusLogs(@PathVariable Long id) {
        logger.info("获取维修申请状态变更记录，申请ID: {}", id);
        List<RepairStatusLog> logs = repairApplicationService.getStatusLogs(id);
        return ResponseEntity.ok(logs);
    }
    
    // 获取维修申请统计信息
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getStatistics() {
        logger.info("获取维修申请统计信息");
        Map<String, Object> statistics = repairApplicationService.getStatistics();
        return ResponseEntity.ok(statistics);
    }
    
    // 导出维修申请数据（Excel）
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportRepairs(
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "priority", required = false) String priority,
            @RequestParam(value = "keyword", required = false) String keyword
    ) {
        // 查询数据（可根据参数筛选）
        List<RepairApplication> data = repairApplicationService.exportApplications(status, type, priority, keyword);
        // 构造Excel
        String[] headers = {"申请编号", "申请人", "类型", "地点", "描述", "状态", "优先级", "创建时间"};
        String[] fields = {"applicationNo", "applicantName", "repairType", "location", "description", "status", "priority", "createTime"};
        byte[] excelData = com.smartcampusbackend.util.ExcelUtil.exportToExcel("维修申请", headers, fields, data);
        HttpHeaders headersObj = new HttpHeaders();
        headersObj.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        headersObj.setContentDisposition(ContentDisposition.attachment().filename("维修申请数据.xlsx", StandardCharsets.UTF_8).build());
        return new ResponseEntity<>(excelData, headersObj, org.springframework.http.HttpStatus.OK);
    }
} 